package com.itcast.tanhuaserver.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itcast.tanhua.dubbo.server.api.RecommendUserApi;
import com.itcast.tanhua.dubbo.server.api.UserLikeApi;
import com.itcast.tanhua.dubbo.server.api.UserLocationApi;
import com.itcast.tanhua.dubbo.server.domain.RecommendUser;
import com.itcast.tanhua.dubbo.server.vo.PageInfo;
import com.itcast.tanhua.dubbo.server.vo.UserLocationVo;
import com.itcast.tanhuaserver.domain.Question;
import com.itcast.tanhuaserver.domain.User;
import com.itcast.tanhuaserver.domain.UserInfo;
import com.itcast.tanhuaserver.domain.UserThreadLocal;
import com.itcast.tanhuaserver.enums.SexEnum;
import com.itcast.tanhuaserver.service.*;
import com.itcast.tanhuaserver.vo.*;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @PachageName: com.itcast.tanhuaserver.service.impl
 * @ClassName:
 * @Description: TODO
 * @Author: Hushi
 * @DateTime: 2021/2/1610:14
 * @Version 1.0
 */
@Service
public class TodayBestServiceImpl implements TodayBestService {
    @Autowired
    private UserService userService;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private UserInfoService userInfoService;

    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;

    @Value("${tanhua.sso.default.recommend.users}")
    private String defaultrecommendUsers;

    @Autowired
    private QuestionService questionService;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private RestTemplate restTemplate;

    @Value("${tanhua.sso.url}")
    private String url;

    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Autowired
    private IMService imService;

    @Override
    public TodayBest queryTodayBest(String token) {
        User user = this.userService.queryUserByToken(token);
        if (user == null){
            return null;    //token失效或者非法
        }

        //查询今日佳人(推荐用户)
        TodayBest todayBest = this.recommendUserService.queryTodayBest(user.getId().longValue());
        if (todayBest == null){
            //查询不出来给出默认推荐用户
            todayBest = new TodayBest();
            todayBest.setId(defaultUser);
            todayBest.setFateValue(80L);
        }
        //补充佳人信息
        UserInfo userInfo = this.userInfoService.queryUserInfoById(todayBest.getId());
        if (userInfo == null){
            return null;
        }
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setAge(userInfo.getAge());

        todayBest.setGender(userInfo.getSex() == null ? "man" : userInfo.getSex().getValue() == 1 ? "man" : "woman");
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(),","));
        return todayBest;
    }

    @Override
    public TodayBest queryTodayBest(Long userId) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = this.userInfoService.queryUserInfoById(userId);
        TodayBest todayBest = new TodayBest();
        todayBest.setId(userId);
        todayBest.setAge(userInfo.getAge());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setGender(userInfo.getSex() == null ? "man" : userInfo.getSex().name().toLowerCase());
        todayBest.setTags(StringUtils.split(userInfo.getTags(),","));
        todayBest.setAvatar(userInfo.getLogo());

        double score = this.recommendUserService.queryScore(userId,user.getId().longValue());
        if (score <= 0){
            score = 98;
        }
        todayBest.setFateValue(Double.valueOf(score).longValue());

        return todayBest;
    }

    @Override
    public PageResult queryRecommendation(String token, RecommendUserQueryParam recommendUserQueryParam) {
        User user = this.userService.queryUserByToken(token);
        if (user == null){
            return null; //token失效或者非法
        }

        PageResult pageResult = new PageResult();
        pageResult.setPage(recommendUserQueryParam.getPage());
        pageResult.setPagesize(recommendUserQueryParam.getPagesize());

        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(user.getId(),pageResult.getPage(),pageResult.getPagesize());
        List<RecommendUser> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)){
            //没有查询到推荐的用户列表使用默认推荐用户列表
            String[] splits = StringUtils.split(defaultrecommendUsers, ",");
            for (String split : splits) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setToUserId(Long.valueOf(user.getId()));
                recommendUser.setUserId(Long.valueOf(split));
                recommendUser.setScore(RandomUtils.nextDouble(80,95));
                records.add(recommendUser);
            }
            /*pageResult.setItems(records);
            //return pageResult;*/
        }

        //添加PageResult返回信息
        Set<Long> userIds = new HashSet<>();
        for (RecommendUser record : records) {
            userIds.add(record.getUserId());
        }

        QueryWrapper<UserInfo> query = new QueryWrapper<>();
        query.in("user_id",userIds);

        //性别筛选
        if (StringUtils.isNotEmpty(recommendUserQueryParam.getGender())){
           // query.eq("sex",StringUtils.equals(recommendUserQueryParam.getGender(),"man") ? 1 : 2);
        }

        //城市筛选
        if (StringUtils.isNotEmpty(recommendUserQueryParam.getCity())){
            //query.like("city",recommendUserQueryParam.getCity());
        }

        //年龄筛选
        if (recommendUserQueryParam.getAge() != null){
            //query.le("age",recommendUserQueryParam.getAge());
        }

        List<UserInfo> userInfo = this.userInfoService.queryUserInfoList(query);
        if (CollectionUtils.isEmpty(userInfo)){
            return pageResult;  //没有查询到用户的基本信息
        }

        //给PageResult赋值
        List<TodayBest> list = new ArrayList<>();
        for (UserInfo info : userInfo) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(info.getUserId());
            todayBest.setAvatar(info.getLogo());
            todayBest.setAge(info.getAge());
            todayBest.setGender(info.getSex() == null ? "woman" : info.getSex().getValue() == 1 ? "man" : "woman");
            todayBest.setNickname(info.getNickName());
            todayBest.setTags(StringUtils.split(info.getTags(),","));

            //缘分值
            for (RecommendUser record : records) {
                if (record.getUserId().longValue() == info.getUserId().longValue()){
                    double score = Math.floor(record.getScore());//取整,98.2 -> 98
                    todayBest.setFateValue(Double.valueOf(score).longValue());
                    break;
                }
            }
            
            list.add(todayBest);
        }
        //按照缘分值进行排序
        Collections.sort(list, (o1, o2) -> new Long(o2.getFateValue() - o1.getFateValue()).intValue());
        pageResult.setItems(list);

        return pageResult;
    }

    @Override
    public String queryQuestion(Long userId) {
        Question question = this.questionService.queryQuestion(userId);
        if (null != question){
            return question.getTxt();
        }
        return "我爱你吗?";
    }

    /**
     * 回复陌生人问题，发送消息给对方
     *
     * @param userId
     * @param reply
     * @return
     */
    @Override
    public boolean replyQuestion(Long userId, String reply) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = this.userInfoService.queryUserInfoById(user.getId().longValue());

        //构建消息内容
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId().toString());
        msg.put("nickname", this.queryQuestion(userId));
        msg.put("strangerQuestion", userInfo.getNickName());
        msg.put("reply", reply);

        try {
            String msgStr = MAPPER.writeValueAsString(msg);

            String targetUrl = this.url + "/user/huanxin/messages";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("target", userId.toString());
            params.add("msg", msgStr);

            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, headers);

            ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(targetUrl, httpEntity, Void.class);

            return responseEntity.getStatusCodeValue() == 200;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        User user = UserThreadLocal.get();

        UserLocationVo userLocationVo = this.userLocationApi.queryByUserId(user.getId().longValue());
        Double latitude = userLocationVo.getLatitude();
        Double longitude = userLocationVo.getLongitude();

        List<UserLocationVo> userLocationVoList = this.userLocationApi.queryUserFromLocation(longitude, latitude, Integer.parseInt(distance));
        if (CollectionUtils.isEmpty(userLocationVoList)){
            return Collections.emptyList();
        }

        List<Long> userIds = new ArrayList<>();
        for (UserLocationVo locationVo : userLocationVoList) {
            if (!userIds.contains(locationVo.getUserId())){
                userIds.add(locationVo.getUserId());
            }
        }


        QueryWrapper<UserInfo> query = new QueryWrapper<>();
        query.in("user_id",userIds);
        if (StringUtils.equalsIgnoreCase(gender,"man")){
            query.eq("sex", SexEnum.MAN);
        }
        else{
            query.eq("sex",SexEnum.WOMAN);
        }
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(query);

        List<NearUserVo> nearUserVoList = new ArrayList<>();
        for (UserLocationVo locationVo : userLocationVoList) {
            if (locationVo.getUserId().longValue() == user.getId().longValue()){
                continue;
            }

            for (UserInfo userInfo : userInfoList) {
                if (locationVo.getUserId().longValue() == userInfo.getUserId().longValue()){
                    NearUserVo nearUserVo = new NearUserVo();
                    nearUserVo.setAvatar(userInfo.getLogo());
                    nearUserVo.setNickname(userInfo.getNickName());
                    nearUserVo.setUserId(userInfo.getUserId());
                    nearUserVoList.add(nearUserVo);
                    break;
                }
            }
        }
        return nearUserVoList;
    }

    @Override
    public List<TodayBest> queryCardsList() {
        User user = UserThreadLocal.get();
        int count = 50;

        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(user.getId(), 1, count);
        if (CollectionUtils.isEmpty(pageInfo.getRecords())) {
            //默认推荐列表
            String[] ss = StringUtils.split(defaultrecommendUsers, ',');
            for (String s : ss) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(s));
                recommendUser.setToUserId(user.getId().longValue());
                pageInfo.getRecords().add(recommendUser);
            }
        }

        List<RecommendUser> records = pageInfo.getRecords();
        int showCount = Math.min(10, records.size());

        List<RecommendUser> newRecords = new ArrayList<>();
        for (int i = 0; i < showCount; i++) {
            //随机选出推荐的好友
            newRecords.add(records.get(RandomUtils.nextInt(0, records.size() - 1)));
        }

        List<Long> userIds = new ArrayList<>();
        for (RecommendUser record : newRecords) {
            userIds.add(record.getUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);

        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);
        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBest.setFateValue(0L);

            todayBests.add(todayBest);
        }

        return todayBests;
    }

    @Override
    public Boolean likeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        String id = this.userLikeApi.saveUserLike(user.getId().longValue(), likeUserId);
        if (StringUtils.isEmpty(id)) {
            return false;
        }

        if (this.userLikeApi.isMutualLike(user.getId().longValue(), likeUserId)) {
            //相互喜欢成为好友
            this.imService.contactUser(likeUserId);
        }
        return true;
    }

    @Override
    public Boolean disLikeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        return this.userLikeApi.deleteUserLike(user.getId().longValue(), likeUserId);
    }


}
